<template>
    <div>
    
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item><a href="/">商品管理</a></el-breadcrumb-item>
            <el-breadcrumb-item>商品列表</el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 卡片视图区域 -->
        <el-card>
            <el-row :gutter="20">
                <el-col :span="8" :offset="0">
                    <el-input placeholder="请输入内容" v-model="queryInfo.query"
                    clearable @clear="getUserList"
                    >
                        <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
                    </el-input>
                </el-col>
                <el-col :span="4" :offset="0">
                    <el-button type="primary" @click="goAddpage">添加商品</el-button>
                </el-col>
            </el-row>
             <!-- 用户列表区域 -->
            <el-table :data="userList" border stripe>
                <el-table-column type="index"></el-table-column>
                <el-table-column label="商品名称" prop="goods_name"></el-table-column>
                <el-table-column label="商品价格(元)" prop="goods_price" width="95px"></el-table-column>
                <el-table-column label="商品重量" prop="goods_weight" width="70px"></el-table-column>
                <el-table-column label="创建时间" prop="add_time" width="140px">
                    <template slot-scope="scope"> 
                        <!-- 调用过滤器 -->
                        {{ scope.row.add_time | dateFormat }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="130px">
                    <template slot-scope="scope">
                        <!-- 修改按钮 -->
                        <el-button type="primary" icon="el-icon-edit" size="mini" @click="editDialog(scope.row.goods_id)"></el-button>
                        <!-- 删除按钮 -->
                        <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserById(scope.row.goods_id)"></el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="queryInfo.pagenum"
                :page-sizes="[1, 2, 5, 10]"
                :page-size="queryInfo.pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
            </el-pagination>
        </el-card>

        

        <!-- 修改用户对话框 -->
        <el-dialog title="提示" :visible.sync="editDialogVisible" width="50%" @close="editDialogClose">
            <!-- 内容主题区域 -->
            <el-form :model="editForm" ref="editFormRef" label-width="70px" :rules="addFormRules">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="editForm.username" disabled></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="editForm.email"></el-input>
                </el-form-item>
                <el-form-item label="手机" prop="mobile">
                    <el-input v-model="editForm.mobile"></el-input>
                </el-form-item>
            </el-form>
            <!-- 底部区域 -->
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editUser">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 分配权限弹窗 -->
        <el-dialog
        title="分配权限"
        :visible.sync="dialogVisible"
        width="50%"
        @close="setRoleDialogClose"
        >
            <p>当前用户：{{userInfo.username}}</p>
            <p>当前角色：{{userInfo.role_name}}</p>
            <p>分配新角色：
                <el-select v-model="selectRoleId" placeholder="请选择">
                    <el-option
                    v-for="item in rolesList"
                    :key="item.id"
                    :label="item.roleName"
                    :value="item.id">
                    </el-option>
                </el-select>
            </p>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
    data(){
        // 验证邮箱规则
        var checkEmail = (rule,value,cb) =>{
            // 验证邮箱正则
            const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-z0-9_-])+/
            if(regEmail.test(value)){
                // 合法邮箱
                return cb()
            }
            cb(new Error("请输入合法邮箱"));
        }
         // 验证手机规则
        var checkMobile = (rule,value,cb) =>{
            // 验证邮箱正则
            const regMobile = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
            if(regMobile.test(value)){
                // 合法手机
                return cb()
            }
            cb(new Error("请输入合法手机号码"));
        }
        return {
            queryInfo:{
                query:'',
                pagenum:1,
                pagesize:10
            },
            userList:[],
            total:0,    //总条数
            pagenum:1,  //页数
            addForm:{
                username:'',
                password:'',
                email:'',
                mobile:'',
            },
            // 验证表单对象
            addFormRules:{
                username:[
                    { required: true, message: '请输入登录名称', trigger: 'blur' },
                    { min: 3, max: 10, message: '长度在3到10之间', trigger: 'blur' }
                ],
                password:[
                    { required: true, message: '请输入登录密码', trigger: 'blur' },
                    { min: 6, max: 15, message: '长度在6到15之间', trigger: 'blur' }
                ],
                email:[
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                    { validator:checkEmail, trigger: 'blur' },
                ],
                mobile:[
                    { required: true, message: '请输入手机', trigger: 'blur' },
                    { validator:checkMobile, trigger: 'blur' },
                ]
            },
            editDialogVisible:false,
            editForm:{
                username:'',
                email:'',
                mobile:'',
            },
            dialogVisible:false,
            userInfo:{
                username:'',
                role_name:''
            },
            // 获取所有角色列表
            rolesList:[],
            // 选中的值
            selectRoleId:'',
        }
    },
    created(){
        this.getUserList();
    },
    methods:{
        async getUserList(){
            const {data:res} = await this.$http.get('goods',{ params : this.queryInfo });
            if(res.meta.status != 200){
                return this.$message.error("获取用户列表失败！");
            }
            console.log(res)
            this.userList = res.data.goods;
            this.total = res.data.total;
            this.pagenum = res.data.pagenum;
        },
        handleSizeChange(newSize){
            console.log(newSize);
            this.queryInfo.pagesize = newSize
            this.getUserList()
        },
        handleCurrentChange(newPage){
            console.log(newPage);
            this.queryInfo.pagenum = newPage
            this.getUserList()
        },
        async userStateChange(userInfo){
            console.log(userInfo.mg_state)

            const {data:res} = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`);
            if(res.meta.status !=200) return this.$message.error("用户更新失败")
            this.$message.success("用户更新成功")
        },
        async editDialog(id){
            console.log(id)
            const {data:res} = await this.$http.get('users/'+id)
            if(res.meta.status != 200) return this.$message.error("查询用户信息失败")
            this.editForm = res.data
            this.editDialogVisible = true
        },
        // 提交修改
        editUser(){
             this.$refs.editFormRef.validate( async vaild=>{
                if(!vaild) return
                // 发送请求

                const {data:res} = await this.$http.put('users/'+this.editForm.id,{
                    email:this.editForm.email,
                    mobile:this.editForm.mobile,
                });
                if(res.meta.status != 200) return this.$message.error("修改用户信息失败")
                
                // 关闭弹窗
                this.editDialogVisible = false
                //刷新表格
                this.getUserList();

                this.$message.success("修改用户信息成功！")
            })
        },
        editDialogClose(){
            this.$refs.editFormRef.resetFields()
        },
        async removeUserById(id){
            const confirmResulr = await this.$confirm(
                '此操作将永久删除商品信息，是否继续',
                '提示',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }
            ).catch(err=>err)
            if(confirmResulr!=='confirm') return this.$message.info("已取消删除")
            const {data:res} = await this.$http.delete('goods/'+id)
            if(res.meta.status !== 200) return this.$message.error("用户删除失败")
            this.$message.success("用户删除成功")
            console.log(confirmResulr)
            //刷新表格
            this.getUserList();
        },
        async selectRole(userInfo){
            this.userInfo = userInfo
            // 获取所有角色列表
            const {data:res} = await this.$http.get("roles")
            if(res.meta.status!=200) return this.$message.error("获取角色列表失败")
            this.rolesList = res.data
            this.dialogVisible = true
        },
        // 点击按钮分配角色
        async saveRoleInfo(){
            if(!this.selectRoleId) return this.$message.error("请选择要分配的角色")

            const {data:res} = await this.$http.put(
                `users/${this.userInfo.id}/role`,{
                    rid:this.selectRoleId
                }
            )
            if(res.meta.status !== 200) return this.$message.error("更新角色失败")
            this.$message.success("更新角色成功")
            this.getUserList()
            this.dialogVisible = false
        },
        // 监听分配关闭，重置信息
        setRoleDialogClose(){
            this.userInfo = {}
            this.selectRoleId = ""
        },
        goAddpage(){
            this.$router.push("goods/add")
        }
    }
}
</script>
<style lang="less" scoped>

</style>